<?php

namespace App\Http\Controllers\Admin\Administration;

use App\Exports\OfficeInExport;
use App\Exports\OfficeOutExport;
use App\Http\Controllers\Controller;
use App\Http\Requests\administration\RecordRequest;
use App\Imports\OfficeRecordImport;
use App\Models\administration\OfficeModel;
use App\Models\administration\RecordModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Facades\Excel;

class Record extends Controller
{
    use RecordRequest;

    /**
     * Notes:记录
     * User: xiangzi
     * Date: 2024/9/5
     * Time: 14:35
     * @return \Illuminate\Http\JsonResponse
     */
    public function record($id) {
        $query_enter = RecordModel::query()->with(['office', 'staff', 'dept'])->where('office_id', $id);

        $items_enter = $query_enter->where('type', 1)
            ->orderBy('id', 'desc')
            ->get();

        $list_enter = $items_enter->map(function($item) {
            $res = [
                'id' => $item->id,
                'operation_time' => $item->operation_time,
                'code' => $item->office->code ?? '',
                'name' => $item->office->name ?? '',
                'spe' => $item->office->spe ?? '',
                'number' => $item->number,
                'unit' => $item->office->unit ?? '',
                'price' => $item->price,
                'cost' => $item->cost,
                'channel' => $item->channel,
                'supplier' => $item->supplier,
                'buyer' => $item->staff->name ?? '',
                'dept_name' => $item->dept->name ?? '',
                'reason' => $item->reason,
                'remarks' => $item->remarks,
            ];
            return $res;
        });

        $query_out = RecordModel::query()->where('office_id', $id);

        $items_out = $query_out->where('type', 2)
            ->orderBy('id', 'desc')
            ->get();

        $list_out = $items_out->map(function($item) {
            $res = [
                'id' => $item->id,
                'operation_time' => $item->operation_time,
                'number' => $item->number,
                'take_user' => $item->take_user,
                'remarks' => $item->remarks,
            ];
            return $res;
        });

        return $this->success(['list_enter' => $list_enter, 'list_out' => $list_out]);
    }

    /**
     * Notes:入库
     * User: xiangzi
     * Date: 2024/9/5
     * Time: 14:35
     * @return \Illuminate\Http\JsonResponse
     */
    public function enter(Request $request, $id){
        $auth = $request->get('auth');
        $params = $request->all();

        $check_res = self::enter_check($params);
        if($check_res->faild){
            return $this->error($check_res->err);
        }
        DB::beginTransaction();
        try {
            $model = new RecordModel();
            $model->type = 1;
            $model->office_id = $id;
            $model->price = $params['price'];
            $model->number = $params['number'];
            $model->cost = round($params['price'] * $params['number'], 2);
            $model->channel = $params['channel'] ?? '';
            $model->supplier = $params['supplier'] ?? '';
            $model->staff_id = $params['staff_id'] ?? 0;
            $model->dept_id = $params['dept_id'] ?? 0;
            $model->reason = $params['reason'] ?? '';
            $model->remarks = $params['remarks'] ?? '';
            $model->operation_time = $params['operation_time'];
            $model->created_admin_id = $auth->id;
            $model->save();

            $office = OfficeModel::find($id);
            if (!$office) {
                return $this->error('物品不存在');
            }
            $office->total_purchase_number += $params['number'];
            $office->stock_number += $params['number'];
            $office->save();
            DB::commit();
        }catch (\Exception $e){
            DB::rollBack();
            return $this->error($e->getMessage());
        }

        return $this->success();
    }

    /**
     * Notes:出库
     * User: xiangzi
     * Date: 2024/9/5
     * Time: 14:35
     * @return \Illuminate\Http\JsonResponse
     */
    public function out(Request $request, $id){
        $auth = $request->get('auth');
        $params = $request->all();

        $check_res = self::out_check($params);
        if($check_res->faild){
            return $this->error($check_res->err);
        }

        DB::beginTransaction();
        try {
            $office = OfficeModel::find($id);
            if (!$office) {
                return $this->error('物品不存在');
            }

            if ($office->stock_number < $params['number']) {
                return $this->error('物品库存数量不足');
            }

            $model = new RecordModel();
            $model->type = 2;
            $model->office_id = $id;
            $model->number = $params['number'];
            $model->take_user = $params['take_user'];
            $model->operation_time = $params['operation_time'];
            $model->remarks = $params['remarks'] ?? '';
            $model->created_admin_id = $auth->id;
            $model->save();

            $office->stock_number -= $params['number'];
            $office->save();
            DB::commit();
        }catch (\Exception $e){
            DB::rollBack();
            return $this->error($e->getMessage());
        }

        return $this->success();
    }

    /**
     * Notes:领用申请导入
     * User: xiangzi
     * Date: 2025/4/29
     * Time: 上午11:47
     * @return \Illuminate\Http\JsonResponse
     */
    public function import(Request $request){
        $auth = $request->get('auth');
        $file = $request->file('file');
        if(!$file){
            return $this->error('请选择文件');
        }

        $import = new OfficeRecordImport();
        Excel::import($import, $file);


        $res = $import->get_result();

        if(isset($res->error) && $res->error){
            return $this->error(implode(',', $res->error));
        }

        $lines = $res->lines;

        DB::beginTransaction();
        try {
            foreach ($lines as $line){
                $model = new RecordModel();
                $model->type = 2;
                foreach ($line as $k => $v){
                    $model->$k = $v;
                }
                $model->created_admin_id = $auth->id;
                $model->save();
            }
            DB::commit();
        }catch (\Exception $e){
            DB::rollBack();
            return $this->error($e->getMessage());
        }

        return  $this->success();
    }


    public function export_in(Request $request){
        $id = $request->input('id', '');

        $office = OfficeModel::find($id);

        if (!$office) {
            return $this->error('物品不存在');
        }

        $name = $office->name;

        $query = RecordModel::query()
            ->where('office_id', $id)
            ->where('type', 1)
            ->orderBy('id', 'desc');

        $items = $query->get();

        $list = $items->map(function($item) use ($office) {
            $res = [
                'name' => $office->name,
                'code' => $office->code,
                'spe' => $office->spe,
                'model' => $office->model,
                'unit' => $office->unit,
                'color' => $office->color,
                'price' => $item->price,
                'number' => $item->number,
                'operation_time' => $item->operation_time,
            ];
            return $res;
        });

        $file_name = $name  .'-入库-'.date('Ymd').'.xlsx';
        return Excel::download(new OfficeInExport($list), $file_name);

    }

    public function export_out(Request $request){
        $id = $request->input('id', '');

        $office = OfficeModel::find($id);

        if (!$office) {
            return $this->error('物品不存在');
        }

        $name = $office->name;

        $query = RecordModel::query()
            ->where('office_id', $id)
            ->where('type', 2)
            ->orderBy('id', 'desc');

        $items = $query->get();

        $list = $items->map(function($item) use ($office) {
            $res = [
                'name' => $office->name,
                'code' => $office->code,
                'spe' => $office->spe,
                'model' => $office->model,
                'unit' => $office->unit,
                'color' => $office->color,
                'number' => $item->number,
                'take_user' => $item->take_user,
                'operation_time' => $item->operation_time,
                'remarks' => $item->remarks,
            ];
            return $res;
        });


        $file_name = $name  .'-出库-'.date('Ymd').'.xlsx';
        return Excel::download(new OfficeOutExport($list), $file_name);
    }
}
